import { message } from "antd";
import axios, { AxiosRequestConfig } from "axios";
import { UserInfo } from "./info_modify/InfoModify";
import { UpdatePassword } from "./password_modify/PasswordModify";
import { CreateMeetingRoom } from "./meeting_room_manage/CreateMeetingRoomModal";
import { UpdateMeetingRoom } from "./meeting_room_manage/UpdateMeetingRoom";

const axiosClient = axios.create({
    baseURL: 'http://127.0.0.1:3000/',
    timeout: 3000
})
axiosClient.interceptors.request.use(function (request) {
    const accessToken = localStorage.getItem('access_token');
    if (accessToken) { request.headers.authorization = 'Bearer ' + accessToken; }
    return request;
})
interface PendingTask {
    config: AxiosRequestConfig
    resolve: Function
}
let refreshing = false;
const queue: PendingTask[] = [];
axiosClient.interceptors.response.use(
    undefined,
    async (error) => {

        if (!error.response) { return Promise.reject(error); }

        let { data, config } = error.response;

        if (refreshing && data.code === 401) {
            message.error(data.data);
            return setTimeout(() => {
                window.location.href = '/login';
            }, 1500);
        }

        if (refreshing) {
            return new Promise((resolve) => {
                queue.push({
                    config,
                    resolve
                });
            });
        }

        if (data.code === 401 && !config.url.includes('/user/admin/refresh')) {

            refreshing = true;
            const res = await refreshToken();
            refreshing = false;

            if (res.status === 200) {
                console.log(res);
                queue.forEach(({ config, resolve }) => {
                    resolve(axiosClient(config))
                })

                return axiosClient(config);
            } else {
                message.error(res.data);
                setTimeout(() => {
                    window.location.href = '/login';
                }, 1500);
            }

        } else {
            return error.response;
        }


    }
)
const refreshToken = async () => {

    const res = await axiosClient.get('/user/admin/refresh', {
        params: {
            refreshToken: localStorage.getItem('refresh_token')
        }
    });

    const { data } = res.data;
    localStorage.setItem('access_token', data.access_token);
    localStorage.setItem('refresh_token', data.refresh_token);
    return res;
}





const login = async (username: string, password: string) => {
    return await axiosClient.post('/user/admin/login', {
        username,
        password
    })
}
const userSearch = async (username: string, nickName: string, email: string, pageNo: number, pageSize: number) => {
    return await axiosClient.get('/user/list', {
        params: {
            username,
            nickName,
            email,
            pageNo,
            pageSize
        }
    });
}
const freeze = async (id: number) => {
    return await axiosClient.get('/user/freeze', {
        params: { id }
    });
}





const getUserInfo = async () => {
    return await axiosClient.get('/user/info');
}
const updateInfo = async (data: UserInfo) => {
    return await axiosClient.post('/user/admin/update', data);
}
const updateUserInfoCaptcha = async () => {
    return await axiosClient.get('/user/update/captcha');
}



const updatePasswordCaptcha = async (email: string) =>  {
    return await axiosClient.get('/user/update_password/captcha', {
        params: { email: email }
    });
}

const updatePassword = async (data: UpdatePassword) => {
    return await axiosClient.post('/user/admin/update_password', data);
}

const meetingRoomList = async (name: string, capacity: number, equipment: string, pageNo: number, pageSize: number) => {
    return await axiosClient.get('/meeting-room/list', {
        params: {
            name,
            capacity,
            equipment,
            pageNo,
            pageSize
        }
    });
}

const deleteMeetingRoom = async (id: number) => {
    return await axiosClient.delete('/meeting-room/' + id);
}

const createMeetingRoom = async (meetingRoom: CreateMeetingRoom) => {
    return await axiosClient.post('/meeting-room/create', meetingRoom);
}

const updateMeetingRoom = async (meetingRoom: UpdateMeetingRoom) =>  {
    return await axiosClient.post('/meeting-room/update', meetingRoom);
}

const findMeetingRoom = async(id: number) => {
    return await axiosClient.get('/meeting-room/' + id);
}


export {
    login,
    userSearch,
    freeze,
    getUserInfo,
    updateInfo,
    updateUserInfoCaptcha,
    updatePasswordCaptcha,
    updatePassword,
    meetingRoomList,
    deleteMeetingRoom,
    createMeetingRoom,
    updateMeetingRoom,
    findMeetingRoom
}